package com.wxbus.wxController;



import com.wxbus.daomain.*;
import com.wxbus.service.*;
import com.wxbus.util.JacksonUtil;
import com.wxbus.util.ResponseUtil;
import com.wxbus.util.SortUtil;
import com.wxbus.util.TimeUtil;
import com.wxbus.webController.WebSearchController;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.beans.IntrospectionException;
import java.util.*;

/**
 * Created by g1154 on 2018/5/22.
 */
@RestController
@RequestMapping("/weixin/search")
public class WxSearchController {
    @Autowired
    private DriverService driverService;
    @Autowired
    private PassengerRouteService passenger_routeServise;
    @Autowired
    private CheckServier checkServier;
    @Autowired
    private DriverBusRouteService driverBusRouteService;
    @Autowired
    private StationService stationService;
    @Autowired
    private BusService busService;
    @Autowired
    private RouteService routeService;
    private final Log logger = LogFactory.getLog(WebSearchController.class);

    /**
     *@type method
     *@parameter  [endSiteName]
     *@back  java.lang.Object
     *@author  如花
     *@creattime 2018/5/27
     *@describe 根据站点名称模糊查找站点
     */
    @RequestMapping(value="/site",method={RequestMethod.POST})
    public  Object site(@RequestBody String siteName){
        logger.info("查找站点");
        siteName= JacksonUtil.parseString(siteName,"site");
        if (!"".equals(siteName)){
            List<Station> stationList=stationService.findStationByName(siteName);
            return ResponseUtil.ok(stationList);

        }
        else{
            return ResponseUtil.fail403();
        }

    }

    /**
     *@type method
     *@parameter  [startCoord, endSite, startNum, num]
     *@back  java.lang.Object
     *@author  如花
     *@creattime 2018/5/28
     *@describe 起始点终止点招募线路搜索
     */
    @RequestMapping(value = "/routePlant",method={RequestMethod.POST})
    public Object routePlant(@RequestBody String body){
        Integer passengerCount;
         String endSite=JacksonUtil.parseString(body,"endSite");
        Integer startNum=JacksonUtil.parseInteger(body,"startNum");
        Integer num=JacksonUtil.parseInteger(body,"num");
        String startCoord=JacksonUtil.parseString(body,"startCoord");
        Integer time=JacksonUtil.parseInteger(body,"time");
        logger.info("查找招募线路");
        //起始站点名称
        String startSite=JacksonUtil.parseString(body,"startSite");
        List<Route> routeList=null;
        if(startSite!=null&&"".equals(startSite)){
            if(startSite.equals("我的位置")){
                //查找所有站点
                List<Station> stationList = stationService.findAllStation();
                String [] stringsCoord=startCoord.split(",");
                List<NewStation> newStationList=SortUtil.stationSort(stationList,stringsCoord);
                if(newStationList.get(0)!=null){
                    startSite=newStationList.get(0).getStationName();
                }
            }
        }
        routeList=routeService.findRouteByStartEnd(startSite,endSite, startNum, num,time);
        List<NewRoute> newRouteList=new ArrayList<NewRoute>();
        for(int i=0;i<routeList.size();i++){
            NewRoute newRoute=new NewRoute(routeList.get(i));
            passengerCount=passenger_routeServise.findPassengerCountByRouteId(routeList.get(i).getRouteId());
            newRoute.setPassengerCount(passengerCount);
            newRouteList.add(newRoute);
        }
        return ResponseUtil.ok(newRouteList);
    }

    /**
     *@type method
     *@parameter  [startCoord, endSite, startNum, num]
     *@back  java.lang.Object
     *@author  如花
     *@creattime 2018/5/28
     *@describe 起始点终止点运行线路搜索
     */
    @RequestMapping(value = "/routeRun",method={RequestMethod.POST})
    public Object routeRun(@RequestBody String body){
        Integer passengerCount;
        logger.info("查找已开线路");

        String endSite=JacksonUtil.parseString(body,"endSite");
        Integer startNum=JacksonUtil.parseInteger(body,"startNum");
        Integer num=JacksonUtil.parseInteger(body,"num");
        String startCoord=JacksonUtil.parseString(body,"startCoord");
        //获取时间
        Integer time=JacksonUtil.parseInteger(body,"time");
        //起始站点名称
        String startSite=JacksonUtil.parseString(body,"startSite");


        List<Route> routeList=null;

        if(startSite!=null&&"".equals(startSite)){
            if(startSite.equals("我的位置")){
                //查找所有站点
                List<Station> stationList = stationService.findAllStation();
                String [] stringsCoord=startCoord.split(",");
                List<NewStation> newStationList=SortUtil.stationSort(stationList,stringsCoord);

                if(newStationList.get(0)!=null){
                    startSite=newStationList.get(0).getStationName();
                }
            }
        }

        routeList=routeService.findOpenRouteByStartEnd(startSite,endSite, startNum, num,time);

        List<NewRoute> newRouteList=new ArrayList<NewRoute>();
        for(int i=0;i<routeList.size();i++){
            NewRoute newRoute=new NewRoute(routeList.get(i));
            passengerCount=passenger_routeServise.findPassengerCountByRouteId(routeList.get(i).getRouteId());
            newRoute.setPassengerCount(passengerCount);
            newRouteList.add(newRoute);
        }
        return ResponseUtil.ok(newRouteList);
    }
    @RequestMapping(value = "routeAll",method = RequestMethod.POST)
    /**
     *@type method
     *@parameter  [body]
     *@back  java.lang.Object
     *@author  如花
     *@creattime 2018/6/21
     *@describe 搜索已经运行的线路和正在招募的线路
     */
    public Object routeAll(@RequestBody String body){
        logger.info("搜索已经运行的线路和正在招募的线路");
        String startCoord=JacksonUtil.parseString(body,"startCoord");
        String endSite=JacksonUtil.parseString(body,"endSite");
        String startSite=JacksonUtil.parseString(body,"startSite");
        Integer startNum=JacksonUtil.parseInteger(body,"startNum");
        Integer num=JacksonUtil.parseInteger(body,"num");
        List<Route> routeList=new ArrayList<Route>();
        if("我的位置".equals(startSite)){
            //查找所有站点
            List<Station> stationList = stationService.findAllStation();
            String [] stringsCoord=startCoord.split(",");
            List<NewStation> newStationList=SortUtil.stationSort(stationList,stringsCoord);
            if(newStationList.get(0)!=null){
                startSite=newStationList.get(0).getStationName();
            }
            routeList=routeService.findAllRunWaitRoute(startNum,num,startSite,endSite);
            return ResponseUtil.ok(routeList);

        }
        routeList= routeService.findAllRunWaitRoute(startNum,num,startSite,endSite);
        return ResponseUtil.ok(routeList);
    }

    /**
     *@type method
     *@parameter  [body]
     *@back  java.lang.Object
     *@author  如花
     *@creattime 2018/6/25
     *@describe 司机查找车辆绑定信息
     */
    @RequestMapping(value = "findBusInfo",method = RequestMethod.POST)
    public Object findBusInfo(@RequestBody String body, HttpServletRequest request){
        logger.info("司机查找车辆绑定信息");
        String json= UserTokenManager.getUserId(request.getHeader(HeadersName.TOKEN));
        if("乘客".equals(JacksonUtil.parseString(json,"user"))){
            return ResponseUtil.fail401();
        }
        Integer driverNum=JacksonUtil.parseInteger(json,"userId");
        Driver driver=driverService.findDriverByDriverNum(driverNum);
        if(driver==null){
            return ResponseUtil.fail(500,"未找到相关司机信息");
        }
        String driverId=driver.getDriverId();
        List<DriverBusRoute > list=driverBusRouteService.findInfoByDriverId(driverId);
        if(list==null||list.size()<=0){
            return  ResponseUtil.fail(500,"未找到相关绑定信息");
        }
        DriverBusRoute driverBusRoute=new DriverBusRoute();
        for(int i=0;i<list.size();i++){
            if(list.get(i).getDriverOutTime()==null){
                driverBusRoute=list.get(i);
            }
        }
        Integer routeId=driverBusRoute.getRouteId();
        String busId=driverBusRoute.getBusId();
        Route route=routeService.findRouteById(routeId);
        if(route==null){
            return ResponseUtil.fail(500,"未找到相关线路");
        }
        Bus bus=busService.findBusById(busId);
        if(bus==null){
            return ResponseUtil.fail(500,"未找到相关车辆");
        }
        Map<Object,Object> map=new HashMap<Object, Object>();
        map.put("busId",bus.getBusId());
        map.put("engineNum",bus.getEngineNum());
        map.put("characters",bus.getCharacters());
        map.put("registrationDate",bus.getRegistrationDate());
        map.put("oppenDate",bus.getOppenDate());
        map.put("busOwner",bus.getBusOwner());
        map.put("seating",bus.getSeating());
        map.put("busStatus",bus.getBusStatus());
        map.put("model",bus.getModel());
        map.put("road",routeId+"号线("+route.getStartSite()+","+route.getEndSite()+")");
        return ResponseUtil.ok(map);
    }
    /**
     *@type method
     *@parameter  [request]
     *@back  java.lang.Object
     *@author  如花
     *@creattime 2018/6/26
     *@describe 查看司机的历史任务记录
     */
    @PostMapping(value = "findTask")
    public Object findTask(HttpServletRequest request){
        logger.info("查看司机的历史任务记录");
        String json= UserTokenManager.getUserId(request.getHeader(HeadersName.TOKEN));
        if("乘客".equals(JacksonUtil.parseString(json,"user"))){
            return ResponseUtil.fail401();
        }
        Integer driverNum=JacksonUtil.parseInteger(json,"userId");
        Driver driver= driverService.findDriverByDriverNum(driverNum);
        if(driver==null){
            return  ResponseUtil.fail(500,"未找到相关司机");
        }
        List<DriverBusRoute> list1=driverBusRouteService.findInfoByDriverId(driver.getDriverId());
        List<DriverBusRoute> list2=new ArrayList<>();
        if(list1==null){
            return ResponseUtil.fail(500,"不存在历史信息");
        }
        for(int i=0;i<list1.size();i++){
            if(list1.get(i).getDriverOutTime()!=null){
                list2.add(list1.get(i));
            }
        }
        List<Route> routeList=new ArrayList<>();
        //将对应线路放入routeList
        for(int i=0;i<list2.size();i++){
            Route route=routeService.findRouteById(list2.get(i).getRouteId());
            routeList.add(route);
        }
        return ResponseUtil.ok(routeList);
    }
    /**
     *@type method
     *@parameter  [request]
     *@back  java.lang.Object
     *@author  如花
     *@creattime 2018/6/26
     *@describe 查看司机的某天历史任务记录
     */
    @PostMapping(value = "findTaskByTime")
    public Object findTaskByTime(@RequestBody String body, HttpServletRequest request){
        logger.info("查看司机的某天历史任务记录");
        String json= UserTokenManager.getUserId(request.getHeader(HeadersName.TOKEN));
        if("乘客".equals(JacksonUtil.parseString(json,"user"))){
            return ResponseUtil.fail401();
        }
        Integer driverNum=JacksonUtil.parseInteger(json,"userId");
        Driver driver= driverService.findDriverByDriverNum(driverNum);
        String timeString =JacksonUtil.parseString(body,"time")+" 23:59:59";
        //时间转为date格式
        Date date= TimeUtil.getTimeByString(timeString,"yyyy-MM-dd HH:mm:ss");
//        Calendar calendar=Calendar.getInstance();
        System.out.println(date);
        if(driver==null){
            return  ResponseUtil.fail(500,"未找到相关司机");
        }
        List<DriverBusRoute> list1=driverBusRouteService.findInfoByDriverId(driver.getDriverId());
        List<DriverBusRoute> list2=new ArrayList<>();
        if(list1==null){
            return ResponseUtil.fail(500,"不存在历史信息");
        }
        for(int i=0;i<list1.size();i++){
            //绑定时间在当前时间之前切未解绑
            if(list1.get(i).getDriverOutTime()==null){
                if(list1.get(i).getDirverTime().before(date)){
                    list2.add(list1.get(i));
                }
            }else{
                if(list1.get(i).getDirverTime().before(date)&&list1.get(i).getDriverOutTime().after(date)){
                    list2.add(list1.get(i));
                }
            }
        }
        if(list2==null||list2.size()<=0){
            return ResponseUtil.fail(500,"此司机当天没有开车");
        }
        List<Route> routeList=new ArrayList<>();
        //将对应线路放入routeList
        for(int i=0;i<list2.size();i++){
            Route route=routeService.findRouteById(list2.get(i).getRouteId());
            routeList.add(route);
        }
        return ResponseUtil.ok(routeList);
    }
    @PostMapping(value = "findCurrentRoad")
    /**
     *@type method
     *@parameter  [request]
     *@back  java.lang.Object
     *@author  如花
     *@creattime 2018/6/27
     *@describe 查找指定司机的当前任务
     */
    public Object findCurrentRoad(HttpServletRequest request){
        logger.info("查找司机的当前任务");
        String json= UserTokenManager.getUserId(request.getHeader(HeadersName.TOKEN));
        if("乘客".equals(JacksonUtil.parseString(json,"user"))){
            return ResponseUtil.fail401();
        }
        Integer driverNum=JacksonUtil.parseInteger(json,"userId");
        Driver driver= driverService.findDriverByDriverNum(driverNum);
        if(driver==null){
            return  ResponseUtil.fail(500,"未找到相关司机");
        }
        List<DriverBusRoute> list=driverBusRouteService.findInfoByDriverId(driver.getDriverId());
        if(list==null||list.size()<=0){
            return  ResponseUtil.fail(500,"不存在相关司机信息");
        }
        DriverBusRoute driverBusRoute=new DriverBusRoute();
        for(int i=0;i<list.size();i++){
            if(list.get(i).getDriverOutTime()==null){
                driverBusRoute=list.get(i);
            }
        }
        Integer routeId=driverBusRoute.getRouteId();
        Route route=routeService.findRouteById(routeId);
        if(route==null){
            return ResponseUtil.fail();
        }
        Map<Object,Object> map1=new HashMap<>();
        Map<Object,Object> map2=new HashMap<>();
        String stationId=route.getStationId();
        List mapList=new ArrayList<>();
        if(stationId!=null&&"".equals(stationId)){
            for(String staId:stationId.split(",")){
                Integer id= Integer.parseInt(staId);
                Station station=stationService.findStationById(id);
                map2.put("stationid",station.getStationId());
                map2.put("stationname",station.getStationName());
            }
        }
        map1.put("startSite",route.getStartSite());
        map1.put("endSite",route.getEndSite());
        map1.put("startTime",route.getStartTime());
        map1.put("endTime",route.getEndTime());
        map1.put("busId",driverBusRoute.getBusId());
        if(map2.size()>0){
            mapList.add(map2);
            map1.put("site",mapList);
        }
        return ResponseUtil.ok(map1);
    }
}
